/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Control;

import clases.BookBean;
import clases.Servicios;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 *
 * @author Carolina
 */
public class BooksServlets extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, Exception {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession( false );
        System.out.println("entre");
        Servicios serv = new Servicios();
        String isbn = request.getParameter("isbn");
      
        if (isbn == null) {
            
            List titles = serv.listaTitles();
            request.setAttribute("titles", titles);
            System.out.println("");
            RequestDispatcher dispatcher = request.getRequestDispatcher("/books.jsp");
            dispatcher.forward(request, response);
        }else{
                  System.out.println("isbn: +" +isbn);
             
            BookBean book =   serv.obtenerbook(isbn);
            session.setAttribute( "bookToAdd", book );
         try {
                // get a DocumentBuilderFactory for creating
                // a DocumentBuilder (i.e., an XML parser)
                DocumentBuilderFactory factory =
                        DocumentBuilderFactory.newInstance();

                // get a DocumentBuilder for building the DOM tree
                DocumentBuilder builder =
                        factory.newDocumentBuilder();

                // create a new Document (empty DOM tree)
                Document messageDocument = builder.newDocument();

                // get XML from BookBean and append to Document
                Element bookElement = book.getXML(messageDocument);
                messageDocument.appendChild(bookElement);

                // get PrintWriter for writing data to client
                response.setContentType("text/html");
                out = response.getWriter();

                // open InputStream for XSL document
                InputStream xslStream =
                        getServletContext().getResourceAsStream(
                        "/book.xsl");

                // transform XML document using XSLT
                transform(messageDocument, xslStream, out);

                // flush and close PrintWriter
                out.flush();
                out.close();
            } // catch XML parser exceptions
            catch (ParserConfigurationException pcException) {
                pcException.printStackTrace();
            }
        } }

        // transform XML document using provided XSLT InputStream
        // and write resulting document to provided PrintWriter
    

   
 private void transform(Document document,
            InputStream xslStream, PrintWriter output) {
        try {
            // create DOMSource for source XML document
            Source xmlSource = new DOMSource(document);

            // create StreamSource for XSLT document
            Source xslSource =
                    new StreamSource(xslStream);

            // create StreamResult for transformation result
            Result result = new StreamResult(output);

            // create TransformerFactory to obtain a Transformer
            TransformerFactory transformerFactory =
                    TransformerFactory.newInstance();

            // create Transformer for performing XSL transformation
            Transformer transformer =
                    transformerFactory.newTransformer(xslSource);

            // perform transformation and deliver content to client
            transformer.transform(xmlSource, result);
        } // handle exception when transforming XML document
        catch (TransformerException transformerException) {
            transformerException.printStackTrace(System.err);
        }
    }


    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (Exception ex) {
            Logger.getLogger(BooksServlets.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (Exception ex) {
            Logger.getLogger(BooksServlets.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
